﻿#include "logger.h"

extern "C" Q_DECL_EXPORT ILogger* GetInstance()
{
    return dynamic_cast<ILogger*>(Logger::GetInstance());
}


Logger::Logger()
{
    m_IsOpenLog = false;
    m_pFramework = NULL;
}

Logger::~Logger()
{

}

int Logger::Init()
{
    connect(this, &Logger::sigPostTrdMsg, this, &Logger::slotGetTrdMsg);
    this->moveToThread(&m_thread);
    // create log file
    if(!QFile::exists("./Log")){
        QDir dir;
        dir.mkdir("./Log");
    }
    QDateTime time = QDateTime::currentDateTime();
    QString strfile = QString("./Log/%0.txt").arg(time.toString("yyyyMMdd_hhmm"));
    m_file.setFileName(strfile);
    if(m_file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
    {
        m_file.write("Logger::Init() \t\n");
        m_file.flush();
        m_IsOpenLog = true;
        //start thread
        m_thread.start();
    }
    return 1;
}

int Logger::UnInit()
{
    m_thread.quit();
    if(m_thread.wait())
    {
        m_thread.terminate();
        m_thread.wait(3000);
    }
    if(m_IsOpenLog){
        m_file.close();
        m_IsOpenLog = false;
    }
    return 1;
}

int Logger::SetFramework(IFramework *pFrm)
{
    m_pFramework = pFrm;
    return 1;
}

void Logger::WriteLog(QString szLog)
{
    emit sigPostTrdMsg(logger_log, szLog);
}

void Logger::writeLogger(const char *szLog)
{
    if(m_IsOpenLog)
    {
        QDateTime time = QDateTime::currentDateTime();
        QString strTimer = time.toString("yyyy-MM-dd hh:mm:ss");
        m_szLog = QString("Log[%0]:%2 \t\n")
                .arg(strTimer)
                .arg(szLog);
        m_file.write(m_szLog.toUtf8().data());
        m_file.flush();
        qDebug() << m_szLog.toUtf8().data();
    }
}

void Logger::slotGetTrdMsg(int nType, QString msg)
{
    qDebug() << "Logger::slotGetTrdMsg thread id=" << QThread::currentThreadId();
    switch (nType)
    {
    case logger_log:
    {
        writeLogger(msg.toUtf8().data());
    }
        break;
    default:break;
    }
}
